<script setup lang="ts">
import { computed, reactive, ref, watch } from 'vue';
import { useFormRules, useNaiveForm } from '@/hooks/common/form';
import { $t } from '@/locales';
import { DICT_TYPE, getIntDictOptions } from '@/utils/dict';
import type { Post } from '@/service/api';
import { createPost, updatePost } from '@/service/api';

defineOptions({
  name: 'PostOperateModel'
});

interface Props {
  /** the type of operation */
  operateType: NaiveUI.TableOperateType;
  /** the edit row data */
  rowData?: Post | null;
}

const props = defineProps<Props>();

interface Emits {
  (e: 'submitted'): void;
}

const emit = defineEmits<Emits>();

const visible = defineModel<boolean>('visible', {
  default: false
});

const { formRef, validate, restoreValidation } = useNaiveForm();
const { defaultRequiredRule } = useFormRules();

const submitLoading = ref(false);

const title = computed(() => {
  const titles: Record<NaiveUI.TableOperateType, string> = {
    add: $t('page.manage.post.addPost'),
    edit: $t('page.manage.post.editPost')
  };
  return titles[props.operateType];
});

type Model = Pick<Post, 'id' | 'name' | 'code' | 'remark' | 'status' | 'sort'>;

const model: Model = reactive(createDefaultModel());

function createDefaultModel(): Model {
  return {
    id: 0,
    name: '',
    code: '',
    remark: '',
    status: 1,
    sort: 0
  };
}

type RuleKey = Exclude<keyof Model, 'id' | 'remark'>;

const rules: Record<RuleKey, App.Global.FormRule> = {
  name: defaultRequiredRule,
  code: defaultRequiredRule,
  status: defaultRequiredRule,
  sort: defaultRequiredRule
};

function handleInitModel() {
  Object.assign(model, createDefaultModel());

  if (props.operateType === 'edit' && props.rowData) {
    Object.assign(model, props.rowData);
  }
}

function closeDrawer() {
  submitLoading.value = false;
  visible.value = false;
}

async function handleSubmit() {
  await validate();

  submitLoading.value = true;

  if (props.operateType === 'edit') {
    const { error } = await updatePost(model.id, model);

    if (!error) {
      window.$message?.success($t('common.updateSuccess'));
      closeDrawer();
      emit('submitted');
    }
  } else {
    const { error } = await createPost(model);
    if (!error) {
      window.$message?.success($t('common.addSuccess'));
      closeDrawer();
      emit('submitted');
    }
  }
}

watch(visible, () => {
  if (visible.value) {
    handleInitModel();
    restoreValidation();
  }
});
</script>

<template>
  <NModal v-model:show="visible" :title="title" preset="card" class="w-200">
    <NScrollbar class="h-500px pr-20px">
      <NForm ref="formRef" :model="model" :rules="rules" label-placement="left" :label-width="80">
        <NFormItem :label="$t('page.manage.post.name')" path="name">
          <NInput v-model:value="model.name" :placeholder="$t('page.manage.post.form.name')" />
        </NFormItem>
        <NFormItem :label="$t('page.manage.post.code')" path="code">
          <NInput v-model:value="model.code" :placeholder="$t('page.manage.post.form.code')" />
        </NFormItem>
        <NFormItem :label="$t('page.manage.post.sort')" path="sort">
          <NInputNumber v-model:value="model.sort" :placeholder="$t('page.manage.post.form.sort')" />
        </NFormItem>
        <NFormItem :label="$t('page.manage.post.status')" path="status">
          <NRadioGroup v-model:value="model.status">
            <NRadio
              v-for="item in getIntDictOptions(DICT_TYPE.COMMON_STATUS)"
              :key="item.value"
              :value="item.value"
              :label="item.label"
            />
          </NRadioGroup>
        </NFormItem>
        <NFormItem :label="$t('page.manage.post.remark')" path="remark">
          <NInput v-model:value="model.remark" type="textarea" :placeholder="$t('page.manage.post.form.remark')" />
        </NFormItem>
      </NForm>
    </NScrollbar>
    <template #footer>
      <NSpace justify="end" :size="16">
        <NButton @click="closeDrawer">{{ $t('common.cancel') }}</NButton>
        <NButton type="primary" :loading="submitLoading" @click="handleSubmit">{{ $t('common.confirm') }}</NButton>
      </NSpace>
    </template>
  </NModal>
</template>

<style scoped></style>
